/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wanhai.itm.converter;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.Converter;
import org.zkoss.zk.ui.Component;

/**
 *
 * @author m2434
 */
public class DateConverter implements Converter{
    public Object coerceToUi(Object val, Component comp, BindContext ctx){
//        System.out.println("in DateConveter toUI");
        String format = ctx.getConverterArg("format") != null ? (String) ctx.getConverterArg("format") : "yyyyMMdd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String dateStr = (String) val;
        Date date = null;
        
        try{
            if(dateStr != null) date = sdf.parse(dateStr);
        }catch(Exception e){
            System.out.println("DateConveter error");
        }
        
        return date;
    }
     
    public Object coerceToBean(Object val, Component comp, BindContext ctx) {
//        System.out.println("in DateConveter toBean");
        String format = ctx.getConverterArg("format") != null ? (String) ctx.getConverterArg("format") : "yyyyMMdd";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = (Date) val;
        
        if(val == null){
            return null;
        }else{
            return sdf.format(date);
        }
    }
}
